#coding:utf-8
import appMain as appMain
from flask import request
import hashlib
import wxMsg.sendWxTemplate as wx
import Util.RedisUtil
import Util.MysqlUtil
import wxMsg.weChatDataProcessing as wxData
import xmltodict
import wxMsg.wxSenMsg as wws
import service.UserService as userService
import json
import service.SmsSenMsgService as smsSenMsgService

app =appMain.app
RedisUtilClass = Util.RedisUtil.RedisUtilClass()
MysqlClass = Util.MysqlUtil.MysqlClass()



@app.route("/wx", methods=['POST', 'GET'])
def hello_wold():
    r = request.method
    if "POST" == r:
        print(request.data)
        json = xmltodict.parse(request.data)
        print(json)
        xml = json['xml']
        MsgType = xml['MsgType']
        # 关注/取消关注事件
        if 'event' == MsgType:
            event = xml['Event']
            # 关注事件
            if 'subscribe' == event:
                wxData.save_logIn_user(xml)
                wws.login(xml)
                return wx.sendWxTest(json, "欢迎关注蓝小猫推送公众号,推送功能点击下方官网查询,同时公众号接入微软小冰")
            elif 'SCAN' == event:
                wws.login(xml)
                return wx.sendWxTest(json, "欢迎再次来到蓝小猫推送公众号,,推送功能点击下方官网查询,同时公众号接入微软小冰")
            elif 'unsubscribe' == event:
              # wws.deleteUser(xml)
                return ""
            else:
                return ""
        #elif 'text' == MsgType:
             # 用户发送信息回复
            # return wx.sendWxTest(json, xml['Content'])
        #elif 'image' == MsgType:
            #用户发送的图片
            # return  wx.sendWxTest(json, xml['PicUrl'])

        # return wx.sendWxTest(json, xml['Content'])
        return ""
    else:
        re = handle(request.args)
        return re


@app.route("/exitUser/<token>")
def exitUser(token):
    result = {
        'code': '0',
        'msg': '退出成功'
    }
    RedisUtilClass.delete_key(token)
    return str(result)


@app.route("/getQrcode")
def getQrcode():
    return str(wws.getQrcode())


# title 标题
# content 内容
# secretKey
@app.route("/senMsg/<authCode>", methods=["GET", "POST"])
def senMsg(authCode):
    json = None
    if request.method == "GET":
        json = request.args.to_dict()
    if request.method == "POST":
        if request.content_type.startswith('application/json'):
            json = request.json
        elif request.content_type.startswith('multipart/form-data'):
            json = request.form
        else:
            json = request.values
    json['authCode'] = authCode
    print(json)
    return str(wx.senWxTemplate(json))


@app.route("/queryUserSendMsg/<authCode>", methods=["GET", "POST"])
def queryUserSendMsg(authCode):
    json = None
    if request.method == "GET":
        json = request.args.to_dict()
    if request.method == "POST":
        if request.content_type.startswith('application/json'):
            json = request.json
        elif request.content_type.startswith('multipart/form-data'):
            json = request.form
        else:
            json = request.values
    json['authCode'] = authCode
    return smsSenMsgService.queryDataByAuthCOdeAndId(json)


@app.route("/getUserInfo/<token>")
def getUserInfo(token):
    if RedisUtilClass.getByName(token) is None:
        return str({"code": "0"})
    return str(RedisUtilClass.getByName(token), encoding="utf-8")


@app.route("/uploadAuthCode/<token>")
def uploadAuthCode(token):
    user = RedisUtilClass.getByName(token)
    if (None == user):
        return str({"code": "0", "msg": "修改失败,数据异常"})
    user = str(RedisUtilClass.getByName(token), encoding="utf-8")
    print(user)
    user = json.loads(user.replace("'", '"'))
    print(user['info'])
    userService.updateUserAuthCode(user['info'])
    userinfo = {
        "code": '1',
        'info': user['info']
    }
    RedisUtilClass.setByEx(token, str(userinfo), ex=60 * 60 * 2)
    return str({"code": "1", "msg": "修改成功"})



@app.route("/getUserInfoByOpenId", methods=["GET", "POST"])
def getUserInfoByOpenId():
    comment = None
    if request.method == "GET":
        comment = request.args
    if request.method == "POST":
        if request.content_type.startswith('application/json'):
            comment = request.json
        elif request.content_type.startswith('multipart/form-data'):
            comment = request.form
        else:
            comment = request.values

    return "1111"


@app.route("/aa/<username>")
def hello_wold_aa(username):
    RedisUtilClass.setByEx("token01", username, 10000)
    return 'User %s' % RedisUtilClass.getByName("token")


# 在视图函数中
def handle(request):
    try:
        # 先获取request
        # data = web.input()
        # if len(data) == 0:
        # return "hello, this is handle view"
        signature = request.get("signature")  # 先获取加密签名
        timestamp = request.get("timestamp")  # 获取时间戳
        nonce = request.get("nonce")  # 获取随机数
        echostr = request.get("echostr")  # 获取随机字符串
        token = app.config['WX_TOKEN']  # 自己设置的token
        # 使用字典序排序（按照字母或数字的大小顺序进行排序）
        list = [token, timestamp, nonce]

        list.sort()
        temp = ''.join(list)
        sha1 = hashlib.sha1(temp.encode('utf-8'))
        hashcode = sha1.hexdigest()
        # 将加密后的字符串和signatrue对比，如果相同返回echostr,表示验证成功
        print(hashcode)
        print(signature)
        if hashcode == signature:
            return echostr
        else:
            return ""

    except Exception as e:
        return e
